<?php

namespace App\Http\Middleware;

use App\Models\User;
use Closure;

class WxappMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
//        $date = $request->header('date');
//        $is_log = $request->header('is_log');
//        $openid = $request->header('openid');
        $date = $request->get('date');
        $is_log = $request->get('is_log');
        $openid = $request->get('openid');

//        if ($is_log === null) {
//            return response()->json([
//                'code' => 10002,
//                'msg' => '未找到登录信息',
//                'data' => []
//            ], 400);
//        }
        if ($openid === null) {
            return response()->json([
                'code' => 10002,
                'msg' => '未找到登录信息',
                'data' => []
            ], 401);
        }
        if (!is_string($openid)) {
            return response()->json([
                'code' => 10002,
                'msg' => 'OPENID错误',
                'data' => []
            ], 200);
        }

        $uid = User::where([
            'openid' => $openid
        ])->value('id');

        if (!$uid) {
            return response()->json([
                'code' => 1002,
                'msg' => '未找到登录信息',
                'data' => []
            ], 401);
        }

        $request->merge([
            'auth_uid' => $uid,
            'auth_openid' => $openid
        ]);

        return $next($request);
    }


}
